package com.lastproject.ejb.util;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.TopicDTO;
import com.lastproject.ejb.entities.Category;
import com.lastproject.ejb.entities.Subcategory;
import com.lastproject.ejb.entities.Topic;

/**
 * Session Bean implementation class TopicConversion
 */
@Stateless
@LocalBean
public class TopicConversion {
	@PersistenceContext(unitName = "LastProjectEJB")
	EntityManager em;

	public TopicDTO fromEntity(Topic u) {

		TopicDTO topic = new TopicDTO();
		topic.setId(u.getId());
		topic.setIdCategory(u.getCategory().getId());
		topic.setIdSubcategory(u.getSubcategory().getId());
		
		return topic;
	}

	public Topic fromDTO(TopicDTO u) {
		Topic topic = em.find(Topic.class, u.getId());

		if (topic == null) {
			topic = new Topic();
		}

		topic.setCategory(em.find(Category.class, u.getIdCategory()));
		topic.setSubcategory(em.find(Subcategory.class, u.getIdSubcategory()));		
		return topic;
	}

}
